package com.iwhalecloud.bss.kite.cucc.web.controller.order;

import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IDeliveryService;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.spec.impl.transfer.GoodsInfoTransfer;
import com.iwhalecloud.bss.kite.cucc.web.controller.scene.LocalPersonAttrController;
import com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr.PersonAttrDealService;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.transaction.KiteTransactional;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.SpringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping( {"/delivery"})
@Api(tags = {"/delivery - 收货信息"})
public class DeliveryController {
    @Autowired
    private IDeliveryService deliveryService;
    @Autowired
    private IQuerySceneInstService querySceneInstService;
    @Autowired
    private PersonAttrDealService personAttrDealService;
    @Autowired
    private IOperateSceneInstService operateSceneInstService;
    @KiteTransactional
    @ApiOperation(value = "收货信息属性", notes = "收货信息属性" )
    @PostMapping( {"/operateDeliveryInfos"})
    public DataResult<Map<String, Object>> operateDeliveryInfos(@RequestParam String moduleId, @RequestParam String actionType,@RequestParam(required = false) String instId) {
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        List<KiteOfferInst> mainOfferInstList = querySceneInstService.listMainOfferInsts(sceneInstId);
        KiteOfferInst mainOfferInst = mainOfferInstList.stream()
            .filter(dto -> !GoodsInfoTransfer.isAddRoleOffer(dto.getOfferId(), OfferCache.get(dto.getOfferId()).getCateId()))
            .findFirst().orElse(null);
        String mainOfferInstId = "";
        if (Objects.nonNull(mainOfferInst)){
            mainOfferInstId = mainOfferInst.getOfferInstId();
        }
        return ErrorConsts.SUCCESS.getResult(deliveryService.operateDeliveryInfos(sceneInstId, mainOfferInstId, moduleId, instId,actionType));
    }

    @KiteTransactional
    @ApiOperation(value = "更新收货信息属性", notes = "更新收货信息属性")
    @ApiImplicitParams({@ApiImplicitParam(name = "instId", value = "实例id", required = true),
        @ApiImplicitParam(name = "fieldName", value = "修改字段", required = true),
        @ApiImplicitParam(name = "value", value = "修改值", required = true),
        @ApiImplicitParam(name = "valueDesc", value = "展示值", required = false),
        @ApiImplicitParam(name = "sceneInstId", value = "场景实例id", required = false)
    })
    @PostMapping( {"/updateDeliveryAttr"})
    public DataResult<Boolean> updateDeliveryAttr(@RequestParam String instId ,@RequestParam String fieldName,
                                                              @RequestParam String value, @RequestParam(required = false) String valueDesc, @RequestParam(required = false) String sceneInstId) {
        if(KiteStringUtils.isEmpty(sceneInstId)){
            sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        }
        List<Map<String, Object>> deliveryInfos = querySceneInstService.getExtParameterValue(sceneInstId, "offerInstDeliveryInfos");
        if (KiteListUtils.isEmpty(deliveryInfos)) {
            return ErrorConsts.SUCCESS.getResult(false);
        }

        // 如果收货方式是组合收货,则同步每个收货信息
        boolean hasDelivery = false;
        List<KiteProdInst> prodInstList = querySceneInstService.listProdInsts(sceneInstId);
        for (KiteProdInst prodInst : prodInstList) {
            KiteAttr attr = prodInst.getAttr("200004110");
            if (!KiteObjectUtils.isEmpty(attr)) {
                if (KiteStringUtils.equals(attr.getValue(), "100007295")) {
                    hasDelivery = true;
                    break;
                }
            }
        }

        for (Map<String, Object> delivery : deliveryInfos) {
            if (hasDelivery) {
                setDeliveryAttr(fieldName, value, valueDesc, sceneInstId, delivery);
            }
            else if (KiteStringUtils.isEqual(KiteMapUtils.getString(delivery, "instId"), instId)) {
                setDeliveryAttr(fieldName, value, valueDesc, sceneInstId, delivery);
            }
        }
        operateSceneInstService.putExtParameter(sceneInstId, "offerInstDeliveryInfos", deliveryInfos);
        //收货信息只有一个，保存到对应的业务属性中即可
        LocalPersonAttrController attrController = SpringUtil.getBean(LocalPersonAttrController.class);
        attrController.updateCommonAttr(fieldName, value, valueDesc, LocalKeyConsts.DELIVERYINFO_MODULEID,sceneInstId);
        return ErrorConsts.SUCCESS.getResult(true);
    }

    private void setDeliveryAttr(@RequestParam String fieldName, @RequestParam String value,
        @RequestParam(required = false) String valueDesc, @RequestParam(required = false) String sceneInstId,
        Map<String, Object> delivery) {
        String actionType = (String) delivery.get("actionType");
        if (!KiteStringUtils.equals(actionType, ActionType.A.name())) {
            delivery.put("actionType", "M");
        }
        List<KiteAttr> kiteAttrs = (List<KiteAttr>) delivery.get("kiteAttrs");
        for(KiteAttr attr : kiteAttrs){
            if(KiteStringUtils.isEqual(attr.getFieldName(), fieldName)){
                DataResult<Boolean> apply = personAttrDealService.apply(attr,sceneInstId, fieldName, value, valueDesc);
                if(!apply.getResultObject()){
                    BssException.throwOut("","","处理失败");
                }else{
//                            if(KiteStringUtils.equals(attr.getAttrValueTypeId(), KeyValues.DROPDOWN)){
                    attr.setValueDesc(valueDesc);
//                            }
                    attr.setValue(value);
                }
            }
        }
    }

    @ApiOperation( value = "查询收货信息", notes = "查账收货信息" )
    @GetMapping( {"/listDeliveryInfos"})
    @ApiImplicitParams( {@ApiImplicitParam( name = "sceneInstId", value = "场景实例ID" )})
    public DataResult<Map<String, Object>> getDeliveryInfosList(@RequestParam String sceneInstId) {
        if (KiteStringUtils.isEmpty(sceneInstId)) {
            sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        }
        return ErrorConsts.SUCCESS.getResult(deliveryService.getDeliveryInfosList(sceneInstId));
    }

    @ApiOperation( value = "融合产品自动生成收货信息", notes = "融合产品自动生成收货信息" )
    @GetMapping( {"/autogenerationDeliveryInfos"})
    @ApiImplicitParams( {@ApiImplicitParam( name = "sceneInstId", value = "场景实例ID" )})
    public DataResult<Boolean> autogenerationDeliveryInfos(@RequestParam String sceneInstId) {
        if (KiteStringUtils.isEmpty(sceneInstId)) {
            sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        }
        return ErrorConsts.SUCCESS.getResult(deliveryService.autogenerationDeliveryInfos(sceneInstId));
    }
}
